package com.hkccommunity.controller;


import com.alibaba.fastjson.JSON;
import com.hkccommunity.common.Code;
import com.hkccommunity.common.R;
import com.hkccommunity.dto.ProblemDto;
import com.hkccommunity.entity.Problem;

import com.hkccommunity.entity.User;
import com.hkccommunity.service.AnswerParentService;
import com.hkccommunity.service.ProblemService;
import com.hkccommunity.service.UserService;
import com.hkccommunity.service.impl.AnswerParentServiceImpl;
import com.hkccommunity.service.impl.ProblemServiceImpl;
import com.hkccommunity.service.impl.UserServiceImpl;

import com.hkccommunity.util.DateConversionUtil;
import com.hkccommunity.util.JsonSwitchUtil;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/problem/*")
public class ProblemController extends BaseController{

    private ProblemService problemService = new ProblemServiceImpl();
    private UserService userService = new UserServiceImpl();
    private AnswerParentService parentService = new AnswerParentServiceImpl();

    //增

    public void addProblem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
//        System.out.println(user);
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Problem problem = JSON.parseObject(line, Problem.class);
        problem.setCreateUser(user.getId());
        problem.setReadCount(0L);
        problem.setDelete(0);
        problem.setCreateTime(DateConversionUtil.dateToString());
        int i = problemService.addProblem(problem);
        System.out.println(problem);

        R r = new R();
        if (i > 0){
            r.setCode(Code.POST_SUCCESS);
            r.setMessage("发布成功");
        }else{
            r.setCode(Code.POST_ERROR);
            r.setMessage("发布失败，稍后再试！！！");
        }
        JsonSwitchUtil.toJsonSting(req,resp,r);
    }

    //改

    /**
     * 点击链接增加阅读数
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void updateReadCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取问题ID
        Long problemId = Long.valueOf(req.getParameter("problemId"));

        int i = problemService.updateReadCount(problemId);
//        System.out.println("更新..." + i);
        //创建返回值对象
        R r = new R();
        if (i>1){
            r.setCode(Code.GET_SUCCESS);
            r.setMessage("发布问题成功");
            r.setData(r);
        }else {
            r.setCode(Code.GET_ERROR);
            r.setMessage("发布问题失败！！！");
            r.setData(i);
        }
        JsonSwitchUtil.toJsonSting(req,resp,r);
    }




    //查
    /**
     * 获取当前页码的问题数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void getProblem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String reqParameter1 = req.getParameter("pageNo");
        Integer pageNo = Integer.valueOf(reqParameter1);
        String reqParameter2 = req.getParameter("pageSize");
        Integer pageSize = Integer.valueOf(reqParameter2);

//        System.out.println(reqParameter1 + "...." + reqParameter2);

        List<Problem> problemList = problemService.getProblem((pageNo - 1) * pageSize, pageSize);

        //前端数据模型赋值
        List<ProblemDto> dtoList = new ArrayList<>();
        R r = new R();
        problemList.forEach(problem -> {
            ProblemDto problemDto = new ProblemDto();
            problem.setTitle(problem.getTitle().trim());
            problem.setCreateTime(DateConversionUtil.dateConversion(problem.getCreateTime()));
            //复制父类属性到子类
            try {
                BeanUtils.copyProperties(problemDto,problem);
            } catch (IllegalAccessException e) {
                r.setMessage("系统出错！！！");
                r.setCode(Code.GET_ERROR);
                try {
                    JsonSwitchUtil.toJsonSting(req,resp,r);
                } catch (ServletException ex) {
                    throw new RuntimeException(ex);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            //查找问题创建者
            User user = userService.getUserById(problem.getCreateUser());
            problemDto.setQuestioner(user);

            //查找问题的回答数量
            int count = parentService.getCountByProblem(problem.getProblemId());
//            System.out.println(count);
            problemDto.setAnswerCount(count);
            dtoList.add(problemDto);
        });
        //排序
        dtoList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        //前端传值
        if (dtoList != null){
            r.setCode(Code.GET_SUCCESS);
            r.setData(dtoList);
        }else {
            r.setCode(Code.GET_ERROR);
            r.setMessage("暂未查询到！！！");
        }
        System.out.println(r);
        JsonSwitchUtil.toJsonSting(req,resp,r);

    }

    /**
     * 获取页码相关数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void getPageTool(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int count = problemService.getCount();
        JsonSwitchUtil.toJsonSting(req,resp,count);
    }

    public void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String input = req.getParameter("input");
        List<Problem> problemList = problemService.getProblemByInput("%" + input + "%");

        List<ProblemDto> dtoList = new ArrayList<>();
        R r = new R();
        problemList.forEach(problem -> {
            ProblemDto problemDto = new ProblemDto();
            problem.setTitle(problem.getTitle().trim());
            problem.setCreateTime(DateConversionUtil.dateConversion(problem.getCreateTime()));
            //复制父类属性到子类
            try {
                BeanUtils.copyProperties(problemDto,problem);
            } catch (IllegalAccessException e) {
                r.setMessage("系统出错！！！");
                r.setCode(Code.GET_ERROR);
                try {
                    JsonSwitchUtil.toJsonSting(req,resp,r);
                } catch (ServletException ex) {
                    throw new RuntimeException(ex);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            //查找问题创建者
            User user = userService.getUserById(problem.getCreateUser());
            problemDto.setQuestioner(user);

            //查找问题的回答数量
            int count = parentService.getCountByProblem(problem.getProblemId());
//            System.out.println(count);
            problemDto.setAnswerCount(count);
            dtoList.add(problemDto);
        });
        dtoList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        //前端传值
        if (dtoList != null){
            r.setCode(Code.GET_SUCCESS);
            r.setData(dtoList);
        }else {
            r.setCode(Code.GET_ERROR);
            r.setMessage("暂未查询到！！！");
        }
        System.out.println(r);
        JsonSwitchUtil.toJsonSting(req,resp,r);

    }
}
